/**
 * QUANSHI.com Inc.
 * Copyright (c) 2016-2017 All Rights Reserved.
 */
package com.quanshi.scheduler.core.rpc.netcom.jetty.client;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.quanshi.scheduler.core.rpc.codec.RpcRequest;
import com.quanshi.scheduler.core.rpc.codec.RpcResponse;
import com.quanshi.scheduler.core.rpc.serialize.HessianSerializer;
import com.quanshi.scheduler.core.utils.HttpHelper;

/**
 * Jetty Client
 * 
 * @author chinaxiang
 * @version 2017年7月7日 下午9:59:44
 */
public class JettyClient {

    private static Logger logger = LoggerFactory.getLogger(JettyClient.class);

    public RpcResponse send(RpcRequest request) throws Exception {
        try {
            // serialize request
            byte[] requestBytes = HessianSerializer.serialize(request);
            // remote invoke
            byte[] responseBytes = HttpHelper.postRequest("http://" + request.getServerAddress() + "/", requestBytes);
            if (responseBytes == null || responseBytes.length == 0) {
                RpcResponse rpcResponse = new RpcResponse();
                rpcResponse.setError("RpcResponse byte[] is null");
                return rpcResponse;
            }
            // deserialize response
            RpcResponse rpcResponse = (RpcResponse) HessianSerializer.deserialize(responseBytes, RpcResponse.class);
            return rpcResponse;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            RpcResponse rpcResponse = new RpcResponse();
            rpcResponse.setError("Client-error:" + e.getMessage());
            return rpcResponse;
        }
    }
}
